package com.dqy.twserver.server.handle.ehandle.hook;

import com.dqy.twserver.server.dto.GameDto;
import com.dqy.twserver.server.handle.ehandle.GameEventHandle;
import com.dqy.twserver.server.handle.ehandle.mutil.GameEventInRoomHandle;
import com.dqy.twserver.server.handle.ehandle.mutil.IRoom;
import com.dqy.twserver.server.support.Constans;
import com.dqy.twserver.server.support.MsgPush;
import com.dqy.twserver.server.support.Player;
import com.dqy.twserver.server.support.SupportMap;
import com.dqy.twserver.server.support.data.RoomInfo;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class GameEventPlayUnregisteredHandle implements GameEventHandle, IRoom {
    static Logger logger = LoggerFactory.getLogger(GameEventPlayUnregisteredHandle.class);
    @Override
    public void handle(GameDto req, NioSocketChannel channel) throws Exception {
        String cid = channel.id().toString();
        logger.info("[GameEventPlayUnregisteredHandle] start 客户端连接主动断开...cid={}",cid);

        //清理服务端保留的登录信息
        Map<String, Player> channelIdPlayMap = SupportMap.channelIdPlayMap;
        Map<String, Player> playerMap = SupportMap.playerMap;
        Map<Integer, RoomInfo> roomMap = SupportMap.roomMap;
        Player player = channelIdPlayMap.get(cid);
        if(player!=null){
            playerMap.remove(player.getPlayerName());
            logger.info("{}登录信息清理完毕...",player.getPlayerName());
            int roomId = player.getRoomId();
            RoomInfo roomInfo = roomMap.get(roomId);
            if(roomInfo!=null){
                logger.info("存在房间信息，开始清理玩家房间信息");
                if(roomInfo.getPlayerList().get(0).getPlayerName().equals(player.getPlayerName())){ //该名玩家是房主，清除该房间

                    //发送关闭房间通知
                    MsgPush.sendMsg(roomInfo.getPlayerList(),"[系统通知] 房主断开连接，房间已被强制解散 !", "info", Constans.EVENT_TYPE_SEND_ROOM_IS_CLOSE);
                    roomMap.remove(roomId);
                    return;
                }
                //不是房主，直接清除房间内该玩家信息
                String msgBody=String.format("[系统通知] %s 已断开连接",player.getPlayerName());
                MsgPush.sendMsg(roomInfo.getPlayerList(),msgBody, "info", Constans.EVENT_TYPE_SEND_ALL_MSG);
                roomInfo.getPlayerList().remove(player);

                //同时需要刷新房间内的信息
                String roomInfoStr = getRoomInfo(roomInfo.getPlayerList());
                MsgPush.sendMsg(roomInfo.getPlayerList(),roomInfoStr, "roomListStr", Constans.EVENT_TYPE_SEND_ROOM_INFO);

                logger.info("{}房间信息清理完毕...",player.getPlayerName());
            }
        }
        logger.info("[GameEventPlayUnregisteredHandle] end");
    }
}
